package algotithm.leetcode.dfs.test46;

import java.util.ArrayList;
import java.util.List;

/**
 * @author zhouyanxiang
 * @Date 2021-04-2021/4/6-22:48
 * @Title 46. 全排列
 */
public class Solution {

    public static void main(String[] args) {
        Solution solution = new Solution();
        int[] nums = {1,2,3};
        List<List<Integer>> permute = solution.permute(nums);
        for (List<Integer> list : permute) {
            System.out.println(list);
        }
    }

    public List<List<Integer>> permute(int[] nums) {
        List<List<Integer>> res = new ArrayList<>();
        List<Integer> path = new ArrayList<>();
        int len = nums.length;
        boolean[] used = new boolean[len];
        dfs(nums,len,used,res,path,0);
        return res;
    }

    public void dfs(int[] nums,int len,boolean[] used,List<List<Integer>> res,List<Integer> path,int depth) {
        if (depth == len) {
            res.add(path);
        }
        for (int i = 0; i < len; i++) {
            if (!used[i]) {
                List<Integer> newPath = new ArrayList<>(path);
                newPath.add(nums[i]);
                boolean[] newUsed = new boolean[len];
                System.arraycopy(used,0,newUsed,0,len);
                newUsed[i] = true;
                dfs(nums,len,newUsed,res,newPath,depth+1);
            }
        }
    }

}
